<?php
class CSocialConnecter extends CApplicationComponent
{
    /**
    * array(
        'server' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'oauth'
    );
    * 
    * @var array
    */
    public $storeOptions = array();
    private $_providers=array();
    private $_providerConfig=array();
    private $_store;
    
    public function init()
    {
        parent::init();
    }

    /**
     * Getter magic method.
     * This method is overridden to support accessing providers
     * like reading module properties.
     * @param string $name gateway or property name
     * @return mixed the named property value
     */
    public function __get($name)
    {
        if($this->hasProvider($name))
            return $this->getProvider($name);
        else
            return parent::__get($name);
    }

    /**
     * Checks if a property value is null.
     * This method overrides the parent implementation by checking
     * if the named gateway is loaded.
     * @param string $name the property name or the event name
     * @return boolean whether the property value is null
     */
    public function __isset($name)
    {
        if($this->hasProvider($name))
            return $this->getProvider($name)!==null;
        else
            return parent::__isset($name);
    }

    /**
     * Returns the providers.
     * @param boolean $loadedOnly whether to return the loaded providers only. If this is set false,
     * then all providers specified in the configuration will be returned, whether they are loaded or not.
     * Loaded providers will be returned as objects, while unloaded providers as configuration arrays.
     * This parameter has been available since version 1.1.3.
     * @return array the providers (indexed by their IDs)
     */
    public function getProviders($loadedOnly=true)
    {
        if($loadedOnly)
            return $this->_providers;
        else
            return array_merge($this->_providerConfig, $this->_providers);
    }
    
    /**
     * Sets the providers.
     *
     * When a configuration is used to specify a gateway, it should consist of
     * the provider's initial property values (name-value pairs). Additionally,
     * a gateway can be enabled (default) or disabled by specifying the 'enabled' value
     * in the configuration.
     *
     * If a configuration is specified with an ID that is the same as an existing
     * gateway or configuration, the existing one will be replaced silently.
     *
     * The following is the configuration for two providers:
     * <pre>
     * array(
     *     'google'=>array(
     *         'class'=>'application.extensions.socials.GooglerProvider',
     *         'site_name'=>'https://mysite.com/returnUrl',
     *         'oauth_consumer_key'=>'https://mysite.com/returnUrl',
     *         'oauth_consumer_secret'=>'198BE3F2E8C75A53F38C1C4A5B6DBA27',
     *     ),
     * )
     * </pre>
     *
     * @param array $providers Providers(id=>gateway configuration or instances)
     * @param boolean $merge whether to merge the new gateway configuration with the existing one.
     * Defaults to true, meaning the previously registered gateway configuration of the same ID
     * will be merged with the new configuration. If false, the existing configuration will be replaced completely.
     */
    public function setProviders($providers,$merge=true)
    {
        foreach($providers as $id=>$provider)
        {
            if($provider instanceof IApplicationgateway)
                $this->setProvider($id,$provider);
            else if(isset($this->_providerConfig[$id]) && $merge)
                $this->_providerConfig[$id]=CMap::mergeArray($this->_providerConfig[$id],$provider);
            else
                $this->_providerConfig[$id]=$provider;
        }
    }

    /**
     * Checks whether the named gateway exists.
     * @param string $id application provider ID
     * @return boolean whether the named application provider exists (including both loaded and disabled.)
     */
    public function hasProvider($id)
    {
        return isset($this->_providers[$id]) || isset($this->_providerConfig[$id]);
    }

    /**
     * Retrieves the named application provider.
     * @param string $id application provider ID (case-sensitive)
     * @param boolean $createIfNull whether to create the provider if it doesn't exist yet. This parameter
     * has been available since version 1.0.6.
     * @return IApplicationgateway the application provider instance, null if the application provider is disabled or does not exist.
     * @see hasgateway
     */
    public function getProvider($id,$createIfNull=true)
    {
        if(isset($this->_providers[$id]))
            return $this->_providers[$id];
        else if(isset($this->_providerConfig[$id]) && $createIfNull)
        {
            $config=$this->_providerConfig[$id];
            if(!isset($config['enabled']) || $config['enabled'])
            {
                Yii::trace("Loading \"$id\" application provider",'socials.CSocialConnecter');
                unset($config['enabled']);
                $provider=Yii::createComponent($config);
                return $this->_providers[$id]=$provider;
            }
        }
    }

    /**
     * Puts a gateway under the management of the module.
     * the provider will be initialized by calling its {@link CApplicationComponent::init() init()}
     * method if it has not done so.
     * @param string $id provider ID
     * @param EPayment $provider the provider to be added to the provider.
     * If this parameter is null, it will unload the provider from the module.
     */
    public function setProvider($id,$provider)
    {
        if($provider===null)
            unset($this->_providers[$id]);
        else
        {
            $this->_providers[$id]=$provider;
        }
    }
    
    public function getStore()
    {
        if ($this->_store === null)
        {
//            $this->storeOptions['conn'] = Yii::app()->getDb();
            $this->_store = OAuthStore::instance('PostgreSQL', $this->storeOptions);
            return $this->_store;
        }
        else
        {
            return $this->_store;
        }
    }
}